package com.jl.server;

import com.alibaba.fastjson.JSON;
import com.jl.bean.ProvinceBean;
import com.jl.tool.JDBCconnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class ProvinceServer extends HttpServlet {
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建Connection连接对象
        JDBCconnection jdbCconnection = new JDBCconnection();
        //设置编码为utf-8防止乱码
        resp.setContentType("application/json;charset=utf-8");
        try {
            connection = jdbCconnection.connection();
            statement = connection.createStatement();
            String sql = "select * from provice";
            resultSet = statement.executeQuery(sql);
            ArrayList<ProvinceBean> provinceBeans = new ArrayList<>();
            while (resultSet.next()){
                ProvinceBean provinceBean = new ProvinceBean();
                provinceBean.setId(resultSet.getInt("id"));
                provinceBean.setName(resultSet.getString("name"));
                provinceBeans.add(provinceBean);
            }
            //转成json格式
            String s = JSON.toJSONString(provinceBeans);
            resp.getWriter().write(s);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                resultSet.close();
                statement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }
}
